package com.ytxg.util;

import nl.siegmann.epublib.domain.*;
import nl.siegmann.epublib.epub.EpubReader;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EpubUtils {

    public static List<Pair<String, String>> getContent(String fileName, String bookName) throws Exception {
        List<Pair<String, String>> pairList = new ArrayList<>();//要返回的list
        File file = new File(fileName);//定位文件

        EpubReader reader = new EpubReader();
        Book book = reader.readEpub(new FileInputStream(file));


        List<SpineReference> spineReferences = book.getSpine().getSpineReferences();

        for (SpineReference spineReference : spineReferences) {
            //获取对应resource
            Resource resource = spineReference.getResource();
//            String href = resource.getHref();
//            resources.getByHref(href);

            // 这个内容是html页面
            byte[] data = resource.getData();
            // 文本数据是 只要body 并且把p标签中的class去掉
            String html = new String(data);
            Document doc = Jsoup.parse(html);
//            String title = doc.title();
//            if (!title.equals(bookName)) {
//                continue;
//            }
            String body = doc.body().html();
            Elements ele = doc.body().select("h2.biaoti");
            if (ele.isEmpty()) {
                ele = doc.body().select("h1#calibre_pb_0");
            }
            if (ele.isEmpty()) {
                ele = doc.body().select("h2.BiaoTi2");
            }
            if (ele.isEmpty()) {
                ele = doc.body().select("h2#calibre_pb_3");
            }
            // 找不到章节标题时 给一个默认值
            String name = bookName;
            if (!ele.isEmpty()) {
                name = ele.first().text();
            } else {
                name = doc.title();
            }
            // 不存储非文本数据
            if(doc.body().text().isEmpty()){
                continue;
            }
            String processed = removeEleProp(body);
            Pair<String, String> pair = new Pair<>(name,processed);
            pairList.add(pair);

        }

        return pairList;
    }


    private static final String regEx_tag = "<(\\w[^>|\\s]*)[\\s\\S]*?>";

    public static String removeEleProp(String htmlStr) {
        Pattern p = Pattern.compile(regEx_tag, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(htmlStr);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            String tag = m.group(1);
            m.appendReplacement(sb, "<" + tag + ">");
        }
        m.appendTail(sb);
        return sb.toString();
    }
}
